﻿using System.Collections.Generic;
using System.Windows;
using System.Windows.Data;
using System.Windows.Media;

namespace AmazonGlacierGUI.UI.Infrastructure.MVVMFramework
{
    public class Framework
    {
        public static void BindViewModel(FrameworkElement view,AppViewModelBase vm)
        {
            vm.EnableValidtion = false;
            vm.SetDispacther(view.Dispatcher);
            view.DataContext = vm;
            vm.EnableValidtion = true;
            ((Window) view).Closing += (s, e) =>
            {
                if(!vm.IsCloseRequested)
                {
                    vm.OnClose(); 
                }
            };                       
            vm.OnRequestClose += (s, e) =>
            {
                if(view is Window)
                {
                    ((Window) view).Close();
                }
            };            
            //vm.OnValidateComplete += (s, e) =>
            //{         
                    
            //        //UpdateBindingSources(view);             
            //};
            vm.OnInit();            
        }
        /*
        //http://blogs.msdn.com/b/ryantrem/archive/2010/04/09/globally-updating-binding-sources-in-wpf.aspx
        public static void UpdateBindingSources(DependencyObject dependencyObject)
        {
            foreach (DependencyObject element in EnumerateVisualDescendents(dependencyObject))
            {
                LocalValueEnumerator localValueEnumerator = element.GetLocalValueEnumerator();
                while (localValueEnumerator.MoveNext())
                {
                    BindingExpressionBase bindingExpression = BindingOperations.GetBindingExpressionBase(element, localValueEnumerator.Current.Property);
                    if (bindingExpression != null)
                    {
                        bindingExpression.UpdateSource();
                    }
                }
            }
        }
        public static IEnumerable<DependencyObject> EnumerateVisualDescendents(DependencyObject dependencyObject)
        {
            yield return dependencyObject;

            foreach (DependencyObject child in EnumerateVisualChildren(dependencyObject))
            {
                foreach (DependencyObject descendent in EnumerateVisualDescendents(child))
                {
                    yield return descendent;
                }
            }
        }
        public static IEnumerable<DependencyObject> EnumerateVisualChildren(DependencyObject dependencyObject)
        {
            for (int i = 0; i < VisualTreeHelper.GetChildrenCount(dependencyObject); i++)
            {
                yield return VisualTreeHelper.GetChild(dependencyObject, i);
            }
        }
        */        
    }

}
